package com.google.code.drift.activity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
import com.google.code.drift.R;
import com.google.code.drift.api.AppSkyApp;
import com.google.code.drift.api.UserInfo;
import com.google.code.drift.utils.AudioUtils;
import com.google.code.drift.utils.DLog;
import com.google.code.drift.utils.CommonUtils;

/**
 * @deprecated 已被主界面的地图聊天模式替换
 * @author zkwlx
 * 
 */
public class ChatMapModActivity extends MapActivity {

	private AppSkyApp app;

	private Button refresh;

	private MapView chatMap;

	private boolean isRegistReceiver = false;

	private AudioUtils ring = null;

	private Map<Integer, View> popToUser = new HashMap<Integer, View>();

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.chat_map_mod_layout);

		app = (AppSkyApp) getApplication();
		initView();
		initMapView();
		initChatRing();
		// 重置progress的Handler，达到接管消息的目的
		app.setUpdateUIHandler(new MapChatModHandler());
	}

	@Override
	protected void onStart() {
		IntentFilter filter = new IntentFilter(
				CommonUtils.ACTION_CHAT_MESSAGE_RECEIVER);
		isRegistReceiver = true;
		registerReceiver(chatMessageReceiver, filter);
		super.onStart();
	}

	@Override
	protected void onDestroy() {
		if (isRegistReceiver) {
			unregisterReceiver(chatMessageReceiver);
			isRegistReceiver = false;
			chatMessageReceiver = null;
		}
		if (ring != null) {
			ring.release();
			ring = null;
		}
		if (chatMap != null) {
			chatMap = null;
		}
		if (popToUser != null) {
			popToUser.clear();
			popToUser = null;
		}
		super.onDestroy();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	private void initView() {
		refresh = (Button) findViewById(R.id.chat_map_mod_refresh_button);

		refresh.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				initMapView();
			}
		});

	}

	private void initMapView() {
		if (chatMap == null) {
			chatMap = (MapView) findViewById(R.id.chat_map);
			chatMap.setSatellite(false);
			chatMap.setTraffic(false);
			chatMap.setStreetView(false);
		}

		setMapView();
		initBubbleView();
		initChatBubbleView();
	}

	private void setMapView() {

		GeoPoint point = new GeoPoint(app.getMyInfo().getLatitude(), app
				.getMyInfo().getLongitude());
		List<Overlay> mapOverlays = chatMap.getOverlays();
		mapOverlays.clear();
		MyPlaceOverlay myPlace = new MyPlaceOverlay(point);
		mapOverlays.add(myPlace);

		MapController mapController = chatMap.getController();
		mapController.animateTo(point);
		mapController.setZoom(9);

	}

	private void setMapViewOld() {
		GeoPoint myPoint = new GeoPoint(app.getMyInfo().getLatitude(), app
				.getMyInfo().getLongitude());

		List<Overlay> mapOverlays = chatMap.getOverlays();

		Collection<UserInfo> infoList = app.getMyInfo()
				.getNearbyPersonListFromHashMap();

		MyPlaceOverlay myPlace = new MyPlaceOverlay(myPoint);

		mapOverlays.add(myPlace);
		mapOverlays.addAll(loadPersonInfo(infoList));

		MapController mapController = chatMap.getController();
		mapController.animateTo(myPoint);
		mapController.setZoom(9);
	}

	private void initChatRing() {
		if (app.isChatRing()) {
			ring = new AudioUtils(ChatMapModActivity.this, R.raw.ring);
		}
	}

	private class MyPlaceOverlay extends Overlay {

		private GeoPoint geoPoint = null;

		public MyPlaceOverlay(GeoPoint geoPoint) {
			this.geoPoint = geoPoint;
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			Point point = new Point();
			Projection projection = mapView.getProjection();
			projection.toPixels(geoPoint, point);
			Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
					R.drawable.my_place);
			canvas.drawBitmap(bitmap, point.x, point.y, null);
		}

	}

	private class OtherPlaceOverlay extends Overlay {

		private GeoPoint geoPoint = null;

		private UserInfo info = null;

		public OtherPlaceOverlay(GeoPoint geoPoint, UserInfo info) {
			this.geoPoint = geoPoint;
			this.info = info;
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			Point point = new Point();
			Projection projection = mapView.getProjection();
			projection.toPixels(geoPoint, point);
			Bitmap bitmap = null;
//			if (info.isRoomOwner()) {
//				bitmap = BitmapFactory.decodeResource(getResources(),
//						R.drawable.room_owner_place);
//			} else if (info.isDrifting()) {
//				bitmap = BitmapFactory.decodeResource(getResources(),
//						R.drawable.drifting_person_place);
//			} else {
//				bitmap = BitmapFactory.decodeResource(getResources(),
//						R.drawable.room_person_place);
//			}

			canvas.drawBitmap(bitmap, point.x, point.y, null);

			Paint paint = new Paint();
			paint.setAntiAlias(true);
			paint.setTextSize(20);
			paint.setTextAlign(Align.CENTER);
			canvas.drawText(info.getNick(), point.x, point.y - 10, paint);
		}

	}

	private Collection<Overlay> loadPersonInfo(Collection<UserInfo> infoList) {
		Collection<Overlay> result = new ArrayList<Overlay>();
		Iterator<UserInfo> iterator = infoList.iterator();
		while (iterator.hasNext()) {
			UserInfo info = iterator.next();
			GeoPoint point = new GeoPoint(info.getLatitude(),
					info.getLongitude());
			OtherPlaceOverlay other = new OtherPlaceOverlay(point, info);
			result.add(other);
		}
		return result;
	}

	private void initChatBubbleView() {
		Collection<UserInfo> userList = app.getMyInfo()
				.getNearbyPersonListFromHashMap();
		Iterator<UserInfo> iterator = userList.iterator();
		while (iterator.hasNext()) {
			addChatBubbleView(iterator.next());
		}
		addChatBubbleView(app.getMyInfo());// 这里别忘把自己添加进去
	}

	private void addChatBubbleView(UserInfo user) {
		if (user.isNotDrifting()) {
			// RelativeLayout popView = (RelativeLayout) getLayoutInflater()
			// .inflate(R.layout.chat_bubble_layout, null);
			TextView popView = new TextView(this);
			popView.setGravity(Gravity.CENTER_HORIZONTAL);
			popView.setBackgroundResource(R.drawable.pop_chat);
			popView.setMaxWidth(170);
			GeoPoint geo = new GeoPoint((user.getLatitude()),
					(user.getLongitude()));
			LayoutParams lp = new MapView.LayoutParams(
					MapView.LayoutParams.WRAP_CONTENT,
					MapView.LayoutParams.WRAP_CONTENT, geo,
					MapView.LayoutParams.BOTTOM_CENTER);
			chatMap.addView(popView, lp);
			popView.setVisibility(View.INVISIBLE);
			popToUser.put(user.getUserId(), popView);
		}
	}

	private void initBubbleView() {
		chatMap.removeAllViews();
		Collection<UserInfo> userList = app.getMyInfo()
				.getNearbyPersonListFromHashMap();
		Iterator<UserInfo> iterator = userList.iterator();
		while (iterator.hasNext()) {
			addUserBubbleView(iterator.next());
		}
		// TODO 测试用！
		addUserBubbleView(app.getMyInfo());
	}

	private void addUserBubbleView(final UserInfo user) {
		RelativeLayout bubbleView = (RelativeLayout) getLayoutInflater()
				.inflate(R.layout.user_bubble_layout, null);
		TextView textView = (TextView) bubbleView
				.findViewById(R.id.user_bubble_nick);
		textView.setText(user.getNick());

		GeoPoint geo = new GeoPoint(user.getLatitude(), user.getLongitude());
		LayoutParams lp = new MapView.LayoutParams(
				MapView.LayoutParams.WRAP_CONTENT,
				MapView.LayoutParams.WRAP_CONTENT, geo,
				MapView.LayoutParams.CENTER_HORIZONTAL);
		chatMap.addView(bubbleView, lp);
	}

	private void removePopView(int userId) {
		// 从两个地方删除！
		chatMap.removeView(popToUser.remove(userId));
	}

	private BroadcastReceiver chatMessageReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			DLog.i("MapMod收到聊天消息");
			String string = intent.getStringExtra("json");
			int id = inflatChatBubble(string);

			// 如果不是自己发的，就播放提示音
			if (app.getMyInfo().getUserId() != id && ring != null) {
				// TODO 播放铃声或震动！
				ring.play();
			}
		}
	};

	private int inflatChatBubble(String jsonString) {
		JSONObject json = JSONObject.parseObject(jsonString);
		int id = json.getIntValue("id");
		String content = json.getString("content");
		// RelativeLayout bubble = (RelativeLayout) popToUser.get(id);
		TextView bubble = (TextView) popToUser.get(id);
		bubble.setVisibility(View.VISIBLE);
		// TextView textView = (TextView) bubble
		// .findViewById(R.id.bubble_chat_text);
		bubble.setText(content);
		// textView.setText(content);
		return id;
	}

	/**
	 * 处理用户进入房间和退出房间的事件
	 * 
	 * @author zkwlx
	 * 
	 */
	private class MapChatModHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			String content = bundle.getString("data");
			int duration = bundle.getInt("duration");

			if (msg.what == CommonUtils.CHAT_ACTIVITY_JOIN_ROOM) {
				addChatBubbleView(app.getMyInfo().getUserFromRoomPerson(
						msg.arg1));
			} else if (msg.what == CommonUtils.CHAT_ACTIVITY_QUIT_ROOM) {
				removePopView(msg.arg1);
			}
			showToast(content, duration);
		}
	}

	private void showToast(String content, int duration) {
		Toast.makeText(ChatMapModActivity.this, content, duration).show();
	}

}
